<?php

namespace app\api\service;

use think\Exception;
use think\facade\Cache;

class WeChat
{
    /**
     * @throws Exception
     */
    public static function doLogin($code){
        $config=config('weChat');
        $url='https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$code.'&grant_type=authorization_code';
        $res=self::weiXinApi($url);
        if(!isset($res['openid'])){
            throw new Exception('登录失败，请重试');
        }
        return $res['openid'];
    }

    /**
     * 通过前端code获取手机号
     * @throws Exception
     */
    public static function getPhoneNumberByCode($code){
        try {
            $accessToken=self::getAccessToken();
        }catch (\Exception $e){
            throw new Exception($e->getMessage());
        }
        $url='https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$accessToken;
        $res=self::weiXinApiJson($url,'POST',['code'=>$code]);
        if($res['errcode']!=0){
            throw new Exception('获取手机号失败，请重试');
        }
        return $res['phone_info']['purePhoneNumber'];
    }

    /**
     * 全局access-token控制 获取
     * @throws Exception
     */
    public static function getAccessToken(){
        $accessToken=Cache::get('access_token');
        if(!$accessToken){
            $config=config('weChat');
            $url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$config['appid'].'&secret='.$config['secret'];
            $res=self::weiXinApi($url);
            if(!isset($res['access_token'])){
                throw new Exception('系统繁忙，请稍后重试');
            }
            Cache::set('access_token',$res['access_token'],$res['expires_in']);
            $accessToken=$res['access_token'];
        }
        return $accessToken;
    }
    private static function weiXinApi($url,$method='GET',$data=[]){
        return json_decode(curl_get_contents($url,$method,$data),true);
    }
    private static function weiXinApiJson($url,$method='GET',$data=[]){
        return json_decode(curl_get_contents_json($url,$method,$data),true);
    }
}